package com.sprint.questai.ocrhttp;

import com.sprint.questai.model.dto.response.ChunkResponse;
import com.sprint.questai.module.kb.KnowledgeService;
import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.DocumentSplitter;
import dev.langchain4j.data.document.splitter.DocumentSplitters;
import dev.langchain4j.data.segment.TextSegment;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class OCRServiceHttp {

    private final Tesseract tesseract;
    @Autowired
    private KnowledgeService knowledgeService;

    public OCRServiceHttp() {
        tesseract = new Tesseract();
        //String path=System.getenv("TESSDATA_PREFIX");
        //tesseract.setDatapath("C:\\Program Files (x86)\\Tesseract-OCR\\tessdata");
        // tesseract.setDatapath(path);
        tesseract.setDatapath("src/main/resources/tessdata");
        tesseract.setLanguage("chi_sim"); // 设置语言
    }

    public String processFile(String filePath) {
        File file = new File(filePath);
        String res;
        if (isTextSelectable(file)) {
            res= extractSelectableText(file);
        } else {
            res= processImageFile(file);
        }
        return res;
    }
    public List<ChunkResponse> processFileChunks(String filePath,String knowLedgeId) throws IOException {
        String content=processFile(filePath);
        DocumentSplitter documentSplitter = DocumentSplitters.recursive(400,20);
        List<TextSegment> chunks = documentSplitter.split(Document.from(content));
        //get text
        List<ChunkResponse> res =new ArrayList<>();
        for(TextSegment chunk:chunks){
            ChunkResponse chunkResponse = new ChunkResponse();
            chunkResponse.setText(chunk.text());
            String chunkid = knowledgeService.addChunk(knowLedgeId, chunk.text());
            chunkResponse.setChunkId(chunkid);
            System.out.println("chunkText"+chunk.text());
            res.add(chunkResponse);
        }
        return null;
    }

    /**
     * 提取PDF文件中的可选择文本。
     *
     * @param file PDF文件
     * @return 提取的可选择文本
     */
    private String extractSelectableText(File file) {
        try (PDDocument document = PDDocument.load(file)) {
            PDFTextStripper pdfStripper = new PDFTextStripper();
            return pdfStripper.getText(document);
        } catch (IOException e) {
            throw new OCRProcessingException("Failed to extract selectable text", e);
        }
    }

    /**
     * 使用OCR处理图像文件。
     *
     * @param file 图像文件
     * @return 处理后的文本
     */
    private String processImageFile(File file) {
        try {
            return tesseract.doOCR(file);
        } catch (TesseractException e) {
            throw new OCRProcessingException("Failed to process OCR", e);
        }
    }

    /**
     * 判断PDF文件是否包含可选择的文本。
     *
     * @param file PDF文件
     * @return true 如果包含可选择的文本，false 否则
     */
    private boolean isTextSelectable(File file) {
        try (PDDocument document = PDDocument.load(file)) {
            PDFTextStripper pdfStripper = new PDFTextStripper();
            String text = pdfStripper.getText(document);
            return text.trim().length() > 0; // 如果提取的文本长度大于0个字符
        } catch (IOException e) {
            throw new OCRProcessingException("Failed to check selectable text", e);
        }
    }
}

///**
// * OCRProcessingException 类：用于处理OCR处理中的异常。
// */
//class OCRProcessingException extends RuntimeException {
//    public OCRProcessingException(String message, Throwable cause) {
//        super(message, cause);
//    }
//}
